from service.pconfig import PConfig
from service.rrd import Rrd
from service.PlusterLog import PlusterLog
from MVC.plstdocument import IDocument
import os.path
from PIL import ImageTk
from Tkinter import *
from Tix import ComboBox
import Tix
from tkMessageBox import *

class UserInfoView(Frame,PlusterLog):
    "UserInfoView has same structure as InfoView.Read Info.py first"
    def __init__(self,ctl):
        PlusterLog.__init__(self)
        self.ctl=ctl
        self.name_var=Tix.StringVar()

    def show(self,master=None):
        self.w=Toplevel(master)
        Frame.__init__(self,self.w)
        self.master.title("Cluster & User Information Task")
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        Label(self,text="Select User or Add New User:").grid(row=0,column=0,sticky=W)
        self.name=ComboBox(self,editable=1,command=self.__read_name,\
                           variable=self.name_var)
        user_list=PConfig.attribute.read_user()
        for j in [i for i,m in user_list]:
            self.name.insert(END,j)
        self.name.grid(row=0,column=1,sticky=W)
        self.b_generate=Button(self,text="Add New User",\
                               command=self.__add_user)
        self.b_generate.grid(row=0,column=2)
        self.b_remove=Button(self,text="Remove User",\
                                 command=self.__remove_user)
        self.b_remove.grid(row=0,column=3)
        Label(self,text="User Description:").grid(row=1,column=0,sticky=W)
        self.desc=Entry(self,width=50)
        self.desc.grid(row=1,column=1,columnspan=2,sticky=W)
        Label(self,text="Time span of report:").grid(row=2,sticky=W)
        self.radio_var=StringVar()
        self.radio1=Radiobutton(self,variable=self.radio_var,\
                               value="hour",text="2 hour",\
                                command=self.change_time)
        self.radio1.grid(row=2,column=1,sticky=W)
        self.radio2=Radiobutton(self,variable=self.radio_var,\
                               value="day",text="1 day",\
                                command=self.change_time)
        self.radio2.grid(row=2,column=2,sticky=W)
        self.radio3=Radiobutton(self,variable=self.radio_var,\
                               value="week",text="1 week",\
                                command=self.change_time)
        self.radio3.grid(row=3,column=1,sticky=W)
        self.radio4=Radiobutton(self,variable=self.radio_var,\
                               value="month",text="3 months",\
                                command=self.change_time)
        self.radio4.grid(row=3,column=2,sticky=W)
        self.canvas=Canvas(self,height=500,width=481,\
                           scrollregion=(0,0,500,481))
        self.canvas.grid(row=4,column=0,columnspan=4,sticky=N)

    def __remove_user(self,event=None):
        name=self.name_var.get()
        if name=="":
            showerror("Please select a user")
            return
        self.ctl.handle_remove(name)

    def __add_user(self,event=None):
        desc=self.desc.get()
        if desc=="":
            showerror("Please input user description")
            return
        name=self.name_var.get()
        if name=="":
            showerror("Please input user name")
            return
        self.ctl.handle_add(name,desc)


    def __read_name(self,event=None):
        #TODO here is a very weird problem
        #get(ACTIVE) return Last Active line,not current line
        #Now Fixed
        new_val=self.name.entry.get()
        err=self.ctl.handle_user_display(new_val)

    def change_time(self,event=None):
        time=self.radio_var.get()
        name=self.name_var.get()
        self.ctl.handle_request(name,time)

    def Update(self,doc):
        self.name.slistbox.listbox.delete(0,Tix.END)
        for t in [i for i,m in doc.user_list]:
            self.name.insert(END,t)
        name=doc.user_name
        #self.name_var.set(name)
        self.desc.delete(0,END)
        p=PConfig.attribute.read_desc(name)
        self.desc.insert(END,p)
        png_path=PConfig.attribute.rrd_path+"png/"
        self.cpu_png=ImageTk.PhotoImage(file=png_path+name+"_cpu.png")
        self.mem_png=ImageTk.PhotoImage(file=png_path+name+"_mem.png")
        self.num_png=ImageTk.PhotoImage(file=png_path+name+"_num.png")
        self.canvas.create_image(0,0,image=self.cpu_png,anchor=NW)
        self.canvas.create_image(0,160,image=self.mem_png,anchor=NW)
        self.canvas.create_image(0,320,image=self.num_png,anchor=NW)


class UserInfoAdapter:
    def __init__(self,doc):
        self.doc=doc

    def handle_request(self,name,time_span):
        self.doc.draw_other_time(name,time_span)

    def handle_user_display(self,name):
        self.doc.config(name)
        return self.doc.run()

    def handle_add(self,name,desc):
        self.doc.add_user(name,desc)

    def handle_remove(self,name):
        self.doc.remove_user(name)

class UserInfoTask(IDocument,PlusterLog):
    def __init__(self):
        "The initial user should be whole cluster"
        IDocument.__init__(self)
        PlusterLog.__init__(self)
        self.tool=Rrd.tool
        self.user_name=PConfig.attribute.cluster_name
        self.rrd_path=PConfig.attribute.rrd_path
        self.rrd_png=self.rrd_path+"png/"
        if not os.path.exists(self.rrd_path+self.user_name+".rrd"):
            print "Creating Cluster RRD file:",self.user_name,".rrd"
            self.tool.create_user(self.user_name)
        self.log.debug("UserInfoTask __init__ finish rrd_path %s png %s"%(self.rrd_path,self.rrd_png))
        self.user_list=PConfig.attribute.read_user()

    def config(self,name):
        self.user_name=name

    def add_user(self,name,desc):
        print "add_user",name,desc
        self.user_name=name
        if not desc:
            desc="No Description"
        PConfig.attribute.add_user(name,desc)
        self.user_list=PConfig.attribute.read_user()
        Rrd.tool.create_user(name)
        Rrd.tool.draw_user(name,"-2h","now")
        self.Flush()

    def remove_user(self,name):
        self.user_name = PConfig.attribute.cluster_name
        self.log.info("Remove User %s"%name)
        Rrd.tool.remove_user(name)
        PConfig.attribute.remove_user(name)
        self.user_list=PConfig.attribute.read_user()
        self.Flush()


    def run(self):
        self.log.info("UserInfoTask run")

        for i,j in self.user_list:
            if i==self.user_name:
                rrd=self.rrd_path+self.user_name+".rrd"
                if os.path.exists(rrd):
                    self.tool.draw_user(self.user_name,"-2h","now")
                    self.Flush()
                    return 0
                else:
                    error="No rrd file: %s"%rrd
                    return error
        return "Can not find user. Add that user first"


    def draw_other_time(self,name,time_span):
        if time_span=="hour":
            s="-2h"
        elif time_span=="day":
            s="-1d"
        elif time_span=="week":
            s="-1week"
        elif time_span=="month":
            s="-12week"
        else:
            self.log.error("Time_span error, Use Default -1h")
            s="-2h"
        try:
            Rrd.tool.draw_user(name,s,"now")
        except:
            self.log.error("Draw %s time error"%time_span)
            raise
        self.user_name = name
        self.Flush()
